package com.itheima.server.interceptor;

import com.itheima.commons.utils.JwtUtils;
import com.itheima.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("Authorization");
        //判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken){
            response.setStatus(401);
            return false;
        }
        //解析token。获取里面的信息
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        String phone = (String) claims.get("phone");

        User user = new User();
        user.setId(Long.valueOf(userId));
        user.setMobile(phone);
        UserHolder.set(user);


        //token有效则放行
        return true;
    }
}
